package com.faw.fengyue.rfid.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.hardware.camera2.CameraCaptureSession;
import android.hardware.camera2.CameraDevice;
import android.hardware.camera2.CaptureRequest;
import android.media.ImageReader;
import android.os.Build;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.provider.MediaStore;
import android.util.Log;
import android.util.Size;
import android.view.Surface;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.faw.fengyue.rfid.R;
import com.faw.fengyue.rfid.constants.HttpConstants;
import com.faw.fengyue.rfid.core.JsInterface;
import com.faw.fengyue.rfid.fragment.LoadingFragment;
import com.faw.fengyue.rfid.utils.WebUtils;
import com.faw.fengyue.rfid.utils.log.LogUtil;
import com.faw.fengyue.rfid.utils.sdkinit.XHttp2Init;
import com.faw.fengyue.rfid.utils.sdkinit.XUpdateInit;

import com.symbol.emdk.EMDKManager;
import com.symbol.emdk.EMDKResults;
import com.symbol.emdk.EMDKManager.EMDKListener;
import com.symbol.emdk.EMDKManager.FEATURE_TYPE;
import com.symbol.emdk.barcode.BarcodeManager;
import com.symbol.emdk.barcode.BarcodeManager.ConnectionState;
import com.symbol.emdk.barcode.BarcodeManager.ScannerConnectionListener;
import com.symbol.emdk.barcode.ScanDataCollection;
import com.symbol.emdk.barcode.Scanner;
import com.symbol.emdk.barcode.ScannerConfig;
import com.symbol.emdk.barcode.ScannerException;
import com.symbol.emdk.barcode.ScannerInfo;
import com.symbol.emdk.barcode.ScannerResults;
import com.symbol.emdk.barcode.ScanDataCollection.ScanData;
import com.symbol.emdk.barcode.Scanner.DataListener;
import com.symbol.emdk.barcode.Scanner.StatusListener;
import com.symbol.emdk.barcode.Scanner.TriggerType;
import com.symbol.emdk.barcode.StatusData.ScannerStates;
import com.symbol.emdk.barcode.StatusData;
import com.xuexiang.xutil.tip.ToastUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class MainActivity extends Activity
        implements EMDKListener, DataListener, StatusListener, ScannerConnectionListener {

    private WebView webview;

    private LoadingFragment loadingFragment;

    private long exitTime = 0;

    private static final String APP_CACHE_DIRNAME = "/webcache"; // web缓存目录

    //********* 扫码相关 **********//
    private EMDKManager emdkManager = null;
    private BarcodeManager barcodeManager = null;
    private Scanner scanner = null;
    private List<ScannerInfo> deviceList = null;
    private int scannerIndex = 0; // Keep the selected scanner
    private int defaultIndex = 0; // Keep the default scanner
    private int dataLength = 0;
    private String statusString = "";
    private boolean bSoftTriggerSelected = false;
    private boolean bDecoderSettingsChanged = false;
    private boolean bExtScannerDisconnected = false;
    private final Object lock = new Object();

    //********* 拍照相关 **********//
    private String mCameraId;

    private Size mPreviewSize;

    private ImageReader mImageReader;

    private CameraDevice mCameraDevice;

    private CameraCaptureSession mCaptureSession;

    private CaptureRequest mPreviewRequest;

    private CaptureRequest.Builder mPreviewRequestBuilder;

    private Surface mPreviewSurface;
    private static final String TAG = "MainActivity";
    // 摄像头状态回调
    private final CameraDevice.StateCallback stateCallback = new CameraDevice.StateCallback() {
        @Override
        public void onOpened(CameraDevice camera) {
            mCameraDevice = camera;
            //开启预览
//            startPreview();
        }


        @Override
        public void onDisconnected(@NonNull CameraDevice camera) {
            Log.i(TAG, "CameraDevice Disconnected");
        }

        @Override
        public void onError(@NonNull CameraDevice camera, int error) {
            Log.e(TAG, "CameraDevice Error");
        }
    };

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.d(MainActivity.TAG, "onCreate 被调用");
        super.onCreate(savedInstanceState);
        XHttp2Init.init(this.getApplication());
        XUpdateInit.init(this.getApplication());
        XUpdateInit.checkUpdate(this, HttpConstants.getInstance().getUpdateUrl(), false);

        loadingFragment = new LoadingFragment();

        Window window = getWindow();
        //隐藏标题栏
//        requestWindowFeature(Window.FEATURE_NO_TITLE);//隐藏状态栏
        //定义全屏参数
//        int flag= WindowManager.LayoutParams.FLAG_FULLSCREEN;
        //设置当前窗体为全屏显示
//        window.setFlags(flag, flag);

        setContentView(R.layout.activity_main);


        if (Build.VERSION.SDK_INT >= 21) {
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
//        ActionBar actionBar = getSupportActionBar();
//        actionBar.hide();

        //setContentView(R.layout.activity_main);
        //实例化WebView对象
        webview = new WebView(this);
        String cacheDirPath = getFilesDir().getAbsolutePath() + APP_CACHE_DIRNAME;
        WebUtils.initWebView(webview, cacheDirPath);

        webview.setWebViewClient(new WebViewClient() {
            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);

                int errorCode = error.getErrorCode();
                // 断网或者网络连接超时
                if (errorCode == ERROR_HOST_LOOKUP || errorCode == ERROR_CONNECT || errorCode == ERROR_TIMEOUT) {
//                    view.loadUrl("about:blank"); // 避免出现默认的错误界面
                    view.loadUrl("file:///android_asset/error_network.html");
//                    view.loadUrl(mErrorUrl);
                }
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
//                ToastUtils.toast("开始加载页面");
                // 获取到FragmentManager对象
//                FragmentManager fragmentManager = getSupportFragmentManager();
//                // 开启一个事务
//                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
//                // 显示正在加载组件
//                fragmentTransaction.show(loadingFragment);
//                // 提交事务
//                fragmentTransaction.commit();
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
//                ToastUtils.toast("页面加载完成");
                // 获取到FragmentManager对象
//                FragmentManager fragmentManager = getSupportFragmentManager();
//                // 开启一个事务
//                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
//                // 隐藏正在加载组件
//                fragmentTransaction.hide(loadingFragment);
//                // 提交事务
//                fragmentTransaction.commit();
            }
        });
//        webview.setWebViewClient(new WebViewClient());
        webview.setWebChromeClient(new WebChromeClient());
        webview.addJavascriptInterface(new JsInterface(this), "AndroidInterface");

//        ToastUtils.toast(DeviceIdentifier.getUUID());
//        ToastUtils.toast(Build.BOARD + " \n" + Build.BRAND + " \n" +
//                Build.CPU_ABI + " \n" + Build.DEVICE + " \n" +
//                Build.DISPLAY + " \n" + Build.HOST + " \n" +
//                Build.ID + " \n" + Build.MANUFACTURER + " \n" +
//                Build.MODEL + " \n" + Build.PRODUCT + " \n" +
//                Build.TAGS + " \n" + Build.TYPE + " \n" +
//                Build.USER + " \n");
        //加载需要显示的网页
        loadMainWeb();
        //设置Web视图
        setContentView(webview);
//        ActivityResultLauncher<Intent> cameraLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
//            @Override
//            public void onActivityResult(ActivityResult result) {
//                if (result.getResultCode() == RESULT_OK) {
//                    if (result.getData() != null) {
//                        Log.d(TAG, "onActivityResult: data = " + result.getData().getStringExtra("data_return"));
//                        Bundle extras = result.getData().getExtras();
//                        if (extras != null) {
//                            Bitmap imageBitmap = (Bitmap) extras.get("data");
////                    mImageView.setImageBitmap(imageBitmap);
//                        }
//                    }
//                }
//            }
//        });
//        findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
////                CameraManager cameraManager = (CameraManager) getSystemService(CAMERA_SERVICE);
////                try {
////                    // 遍历所有摄像头
////                    for (String cameraId : cameraManager.getCameraIdList()) {
////                        CameraCharacteristics characteristics = cameraManager.getCameraCharacteristics(cameraId);
////                        // 默认打开后置摄像头 - 忽略前置摄像头
////                        if (characteristics.get(CameraCharacteristics.LENS_FACING) == CameraCharacteristics.LENS_FACING_FRONT) continue;
//////                // 获取StreamConfigurationMap，它是管理摄像头支持的所有输出格式和尺寸
//////                StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
//////                mPreviewSize = getOptimalSize(map.getOutputSizes(SurfaceTexture.class), width, height);
//////                int orientation = getResources().getConfiguration().orientation;
//////                if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
//////                    textureView.setAspectRatio(mPreviewSize.getWidth(), mPreviewSize.getHeight());
//////                } else {
//////                    textureView.setAspectRatio(mPreviewSize.getHeight(), mPreviewSize.getWidth());
//////                }
////                        mCameraId = cameraId;
////                        break;
////                    }
////                } catch (CameraAccessException e) {
////                    throw new RuntimeException(e);
////                }
//                int PERMISSIONS_STORAGE = 100;
//                List<String> permissionLists = new ArrayList<>();
//                if(ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED){
//                    permissionLists.add(Manifest.permission.CAMERA);
//                }
//                if(ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
//                    permissionLists.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
//                }
//                if(ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
//                    permissionLists.add(Manifest.permission.READ_EXTERNAL_STORAGE);
//                }
//                if(!permissionLists.isEmpty()){//说明肯定有拒绝的权限
//                    ActivityCompat.requestPermissions(MainActivity.this, permissionLists.toArray(new String[permissionLists.size()]), PERMISSIONS_STORAGE);
//                } else {
//                    //获得了权限 就做你要做的事了
//                    Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//                    cameraLauncher.launch(intent);
////                        try {
////                            cameraManager.openCamera(mCameraId, stateCallback, null);
////                        } catch (CameraAccessException e) {
////                            throw new RuntimeException(e);
////                        }
//                }
//            }
//        });
//        EMDKResults results = EMDKManager.getEMDKManager(MainActivity.this, this);
//        if (results.statusCode != EMDKResults.STATUS_CODE.SUCCESS) {
//            updateStatus("EMDKManager object request failed!");
//            return;
//        }
    }

//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if(keyCode==KeyEvent.KEYCODE_BACK && webview.canGoBack()){
//            webview.goBack();
//            return true;
//        }else{
//            onBackPressed();
//        }
//        return super.onKeyDown(keyCode, event);
//    }

//    @Override
//    public void onBackPressed() {
//        if (webview.canGoBack()) {
//            webview.goBack();
//        } else {
//            finish();
//        }
//    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
            exitTime = System.currentTimeMillis();
        } else {
            //彻底关闭整个APP
            int currentVersion = Build.VERSION.SDK_INT;
            if (currentVersion > Build.VERSION_CODES.ECLAIR_MR1) {
                Intent startMain = new Intent(Intent.ACTION_MAIN);
                startMain.addCategory(Intent.CATEGORY_HOME);
                startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(startMain);
                System.exit(0);
            } else {// android2.1
                ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
                am.restartPackage(getPackageName());
            }
        }
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {
        super.onCreate(savedInstanceState, persistentState);
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(MainActivity.TAG, "onResume 被调用");
        EMDKResults results = EMDKManager.getEMDKManager(MainActivity.this, this);
        if (results.statusCode != EMDKResults.STATUS_CODE.SUCCESS) {
            updateStatus("EMDKManager object request failed!");
            return;
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d(MainActivity.TAG, "onPause 被调用");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d(MainActivity.TAG, "onStop 被调用");
        // Release all the EMDK resources
        if (emdkManager != null) {
            emdkManager.release();
            emdkManager= null;
        }
        Log.d(MainActivity.TAG , "Main界面的onDestroy执行");
    }

    /**
     * 初始化基础库
     */
//    private void initLibs() {
        // X系列基础库初始化
//        XBasicLibInit.init(this);
        // 版本更新初始化
//        XUpdateInit.init(this);
        // 运营统计数据
//        UMengInit.init(this);
        // ANR监控
//        ANRWatchDogInit.init();
//    }

    // 解决WebView内存泄漏

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if( webview!=null) {
            // 如果先调用destroy()方法，则会命中if (isDestroyed()) return;这一行代码，需要先onDetachedFromWindow()，再
            // destory()
            ViewParent parent = webview.getParent();
            if (parent != null) {
                ((ViewGroup) parent).removeView(webview);
            }

            webview.stopLoading();
            // 退出时调用此方法，移除绑定的服务，否则某些特定系统会报错
            webview.getSettings().setJavaScriptEnabled(false);
            webview.clearHistory();
            webview.clearView();
            webview.removeAllViews();
            webview.destroy();

        }
        deInitScanner();
        // Release all the EMDK resources
        if (emdkManager != null) {
            emdkManager.release();
            emdkManager= null;
        }
        Log.d(MainActivity.TAG , "Main界面的onDestroy执行");
    }

    private void clearWebViewCache() {
        clearCacheX();
        //清除历史数据
        webview.clearHistory();
        //清除 表单数据
        webview.clearFormData();
        // 重新加载页面
        loadMainWeb();
    }
    private void clearCacheX() {
        File file = getCacheDir().getAbsoluteFile();//删除缓存
        deleteFile(file);
    }

    public void deleteFile(File file) {
        if (file.exists()) {
            if (file.isFile()) {
                file.delete();
            } else if (file.isDirectory()) {
                File files[] = file.listFiles();
                for (int i = 0; i < files.length; i++) {
                    deleteFile(files[i]);
                }
            }
            file.delete();
        }
    }

    public void loadMainWeb() {
        webview.loadUrl(HttpConstants.getInstance().getBaseWeb());
    }

    @Override
    public void onOpened(EMDKManager emdkManager) {
//        updateStatus("EMDK open success!");
        this.emdkManager = emdkManager;
        // Acquire the barcode manager resources
        initBarcodeManager();
        // Enumerate scanner devices
        enumerateScannerDevices();
        // Set default scanner
//        spinnerScannerDevices.setSelection(defaultIndex);
        scannerIndex = 1;
        bSoftTriggerSelected = false;
        bExtScannerDisconnected = false;
        deInitScanner();
        initScanner();
    }

    @Override
    public void onClosed() {
        deInitScanner();
        // Release all the resources
        if (emdkManager != null) {
            emdkManager.release();
            emdkManager = null;
        }
        updateStatus("EMDK closed unexpectedly! Please close and restart the application.");
    }

    @Override
    public void onConnectionChange(ScannerInfo scannerInfo, ConnectionState connectionState) {
        String status;
        String scannerName = "";
        String statusExtScanner = connectionState.toString();
        String scannerNameExtScanner = scannerInfo.getFriendlyName();
        if (deviceList.size() != 0) {
            scannerName = deviceList.get(scannerIndex).getFriendlyName();
        }
        if (scannerName.equalsIgnoreCase(scannerNameExtScanner)) {
            switch(connectionState) {
                case CONNECTED:
                    bSoftTriggerSelected = false;
                    synchronized (lock) {
                        initScanner();
                        bExtScannerDisconnected = false;
                    }
                    break;
                case DISCONNECTED:
                    bExtScannerDisconnected = true;
                    synchronized (lock) {
                        deInitScanner();
                    }
                    break;
            }
            status = scannerNameExtScanner + ":" + statusExtScanner;
            updateStatus(status);
        } else {
            bExtScannerDisconnected = false;
            status =  statusString + " " + scannerNameExtScanner + ":" + statusExtScanner;
            updateStatus(status);
        }
    }

    @Override
    public void onData(ScanDataCollection scanDataCollection) {
        if ((scanDataCollection != null) && (scanDataCollection.getResult() == ScannerResults.SUCCESS)) {
            ArrayList <ScanData> scanData = scanDataCollection.getScanData();
            for(ScanData data : scanData) {
//                updateData("<font color='gray'>" + data.getLabelType() + "</font> : " + data.getData());
                updateData(data.getData());
            }
        }
    }

    @Override
    public void onStatus(StatusData statusData) {
        ScannerStates state = statusData.getState();
        switch(state) {
            case IDLE:
                statusString = statusData.getFriendlyName()+" is enabled and idle...";
                updateStatus(statusString);
                // set trigger type
                if(bSoftTriggerSelected) {
                    scanner.triggerType = TriggerType.SOFT_ONCE;
                    bSoftTriggerSelected = false;
                } else {
                    scanner.triggerType = TriggerType.HARD;
                }
                // set decoders
                if(bDecoderSettingsChanged) {
                    setDecoders();
                    bDecoderSettingsChanged = false;
                }
                // submit read
                if(!scanner.isReadPending() && !bExtScannerDisconnected) {
                    try {
                        scanner.read();
                    } catch (ScannerException e) {
                        updateStatus(e.getMessage());
                    }
                }
                break;
            case WAITING:
                statusString = "Scanner is waiting for trigger press...";
                updateStatus(statusString);
                break;
            case SCANNING:
                statusString = "Scanning...";
                updateStatus(statusString);
                break;
            case DISABLED:
                statusString = statusData.getFriendlyName()+" is disabled.";
                updateStatus(statusString);
                break;
            case ERROR:
                statusString = "An error has occurred.";
                updateStatus(statusString);
                break;
            default:
                break;
        }
    }

    private void initScanner() {
        if (scanner == null) {
            if ((deviceList != null) && (deviceList.size() != 0)) {
                if (barcodeManager != null)
                    scanner = barcodeManager.getDevice(deviceList.get(scannerIndex));
            }
            else {
                updateStatus("Failed to get the specified scanner device! Please close and restart the application.");
                return;
            }
            if (scanner != null) {
                scanner.addDataListener(this);
                scanner.addStatusListener(this);
                try {
                    scanner.enable();
                } catch (ScannerException e) {
                    updateStatus(e.getMessage());
                    deInitScanner();
                }
            }else{
                updateStatus("Failed to initialize the scanner device.");
            }
        }
    }

    private void deInitScanner() {
        if (scanner != null) {
            try{
                scanner.disable();
            } catch (Exception e) {
                updateStatus(e.getMessage());
            }

            try {
                scanner.removeDataListener(this);
                scanner.removeStatusListener(this);
            } catch (Exception e) {
                updateStatus(e.getMessage());
            }

            try{
                scanner.release();
            } catch (Exception e) {
                updateStatus(e.getMessage());
            }
            scanner = null;
        }
    }

    private void initBarcodeManager(){
        barcodeManager = (BarcodeManager) emdkManager.getInstance(FEATURE_TYPE.BARCODE);
        // Add connection listener
        if (barcodeManager != null) {
            barcodeManager.addConnectionListener(this);
        }
    }

    private void deInitBarcodeManager(){
        if (emdkManager != null) {
            emdkManager.release(FEATURE_TYPE.BARCODE);
        }
    }

    private void enumerateScannerDevices() {
        if (barcodeManager != null) {
            List<String> friendlyNameList = new ArrayList<String>();
            int spinnerIndex = 0;
            deviceList = barcodeManager.getSupportedDevicesInfo();
            if ((deviceList != null) && (deviceList.size() != 0)) {
                Iterator<ScannerInfo> it = deviceList.iterator();
                while(it.hasNext()) {
                    ScannerInfo scnInfo = it.next();
                    friendlyNameList.add(scnInfo.getFriendlyName());
                    if(scnInfo.isDefaultScanner()) {
                        defaultIndex = spinnerIndex;
                    }
                    ++spinnerIndex;
                }
            }
            else {
                updateStatus("Failed to get the list of supported scanner devices! Please close and restart the application.");
            }
//            ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item, friendlyNameList);
//            spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//            spinnerScannerDevices.setAdapter(spinnerAdapter);
        }
    }

    private void setDecoders() {
        if (scanner != null) {
            try {
                ScannerConfig config = scanner.getConfig();
                // Set EAN8
//                config.decoderParams.ean8.enabled = checkBoxEAN8.isChecked();
//                // Set EAN13
//                config.decoderParams.ean13.enabled = checkBoxEAN13.isChecked();
//                // Set Code39
//                config.decoderParams.code39.enabled= checkBoxCode39.isChecked();
//                //Set Code128
//                config.decoderParams.code128.enabled = checkBoxCode128.isChecked();
                scanner.setConfig(config);
            } catch (ScannerException e) {
                updateStatus(e.getMessage());
            }
        }
    }

    private void updateStatus(final String status){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
//                textViewStatus.setText("" + status);
                ToastUtils.toast(status);
            }
        });
    }

    private void updateData(final String result){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (result != null) {
                    ToastUtils.toast("扫码结果：\n" + result);
                    webview.loadUrl("javascript:OnScanner('"+ result +"')");
//                    if(dataLength ++ > 100) { //Clear the cache after 100 scans
//                        textViewData.setText("");
//                        dataLength = 0;
//                    }
//                    textViewData.append(Html.fromHtml(result));
//                    textViewData.append("\n");
//                    ((View) findViewById(R.id.scrollViewData)).post(new Runnable()
//                    {
//                        public void run()
//                        {
//                            ((ScrollView) findViewById(R.id.scrollViewData)).fullScroll(View.FOCUS_DOWN);
//                        }
//                    });
                }
            }
        });
    }
}
